
def get_rating(item):
    """
    1	刷文章列表
    2	查看文章详情
    3	评论文章
    4	收藏文章
    5	退出文章详情
    6	打开app
    7	隐藏app
    8	取消收藏文章
    input: list of tuple of (user_id, news_id, action, timestamp)
    output: user-news rating matrix
    """
    # TODO：考虑时间调整权重
    # rating计算调整
    # 文章分类、 标签
    # 考虑其他特征如文章停留时长
    # 考虑用户、文章本身特征

    current_time = time.time()

    rating_dict = dict()
    action_score = {1: -1.0, 2: 5.0, 3: 10.0, 4: 20.0, 8: 0}

    user_id = item[0]
    news_id = item[1]
    action = item[2]
    timestamp = item[3]

    if action not in action_score or news_id == 0:  # 暂不考虑的用户操作
        return

    # time_weight = 2/(1 + 1.5**((current_time - timestamp)/86400))
    time_weight = 0.9 ** ((current_time - timestamp) / 86400)

    key = str(user_id) + "," + news_id
    if key not in rating_dict:
        rating_dict[key] = 0.0

    if action == 8:  # 取消收藏重置分数
        rating_dict[key] = 1.0 * time_weight
    else:
        rating_dict[key] += action_score[action] * time_weight

    # # 暂时用dict -> pandas dataframe -> spark dataframe
    # new_rating_dict = {"user_id": [], "news_id": [], "rating": []}
    #
    # for key in rating_dict:
    #     arr = key.split(",")
    #     new_rating_dict["user_id"].append(int(arr[0]))
    #     new_rating_dict["news_id"].append(int(arr[1]))
    #     new_rating_dict["rating"].append(rating_dict[key])
    #
    # ratings = pd.DataFrame(new_rating_dict)
    #
    # mySchema = StructType([StructField("user_id", IntegerType(), True), StructField("news_id", IntegerType(), True),
    #                        StructField("rating", DoubleType(), True)])
    # ratings = spark.createDataFrame(ratings, schema=mySchema)
    #
    # return ratings, user_id_map